package com.kepler.social.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class ShardingHashUtils {

    private static final Logger log = LoggerFactory.getLogger(ShardingHashUtils.class);

    private static final Charset UTF_8 = StandardCharsets.UTF_8;

    public static int toSharding(String key, int tableSize) {
        Assert.isTrue(StringUtils.isNoneBlank(key), "key is blank");
        StringBuilder sb = new StringBuilder();
        int sum = 0;
        for (byte b : key.getBytes(UTF_8)) {
            sum +=b;
        }
        int r =  sum % tableSize;
        log.info("toSharding key {} tableSize {} prex {}", key, tableSize, r);
        return r;
    }

}
